package com.fl.mybatisgenerator.thread;

import com.fl.mybatisgenerator.entity.ThreadData;
import com.fl.mybatisgenerator.mapper.ThreadDataMapper;
import com.fl.mybatisgenerator.service.AsyncService;
import com.fl.mybatisgenerator.service.ThreadDataService;
import javafx.application.Application;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
@ComponentScan("com.fl.mybatisgenerator.service")
public class ThreadPool {

    @Autowired
    private AsyncService asyncService;
    private static Random r= new Random();
    private final static ExecutorService e= new ThreadPoolExecutor(50,
            100,1, TimeUnit.MINUTES,new LinkedBlockingQueue<>(9999));

    @Resource
    private ThreadDataMapper mapper;

    public static void main(String[] args) {
        System.out.println(sendAllMail());
        e.shutdown();
    }

    public static int sendAllMail(){
        List<CompletableFuture<Boolean>> futureList = new ArrayList<>();
        for (int i = 0; i < 500; i++) {
            futureList.add(CompletableFuture.supplyAsync(ThreadPool::sendMail,e));
        }
        //所有都执行完毕
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).join();
        AtomicInteger i = new AtomicInteger(0);
        futureList.forEach(x->{
            try {
                //如果返回值为true 则i加1
                if (x.get()) i.addAndGet(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return i.get();
    }

    public static boolean sendMail(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        boolean b = r.nextBoolean();
        if (b){
//            ThreadData threadData = new ThreadData();
//            threadData.setMsg("自我循环");
//            threadData.setInfo(Thread.currentThread().getName());
//            threadData.setName(Thread.currentThread().getName());
//            service.save(threadData);
            System.out.println("发生成功:->");
        }
        System.out.println("发生失败");
        return b;
    }
    public void testflag(){
        ThreadData threadData = new ThreadData();
        threadData.setMsg("自我循环");
        threadData.setInfo(Thread.currentThread().getName());
        threadData.setName(Thread.currentThread().getName());
//        asyncService.Svein(threadData);
//        service.save(threadData);
        System.out.println(mapper);
    }
}
